package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.widgets.dialog.CustomDialog;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.common.widgets.recycler.RecyclerViewAdapter;
import com.xiaocz.common.widgets.recycler.decoration.DividerItemDecoration;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.adapter.BillingTypeAdapter;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.interfaces.CancelUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.model.BillingType;
import com.xiaocz.hblsubstitutedriving.model.OrderInfo;
import com.xiaocz.hblsubstitutedriving.model.PayReqEntity;
import com.xiaocz.hblsubstitutedriving.model.Reason;
import com.xiaocz.hblsubstitutedriving.widget.ClearTextIconEditText;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;
import com.xiaocz.hblsubstitutedriving.wxapi.Wechat;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 订单收款
 */
public class OrderGatheringActivity extends BaseActivity implements RoundRefresh {

    @BindView(R.id.layout_base)
    RelativeLayout layoutBase;
    @BindView(R.id.layout_wait)
    LinearLayout layoutWait;
    @BindView(R.id.tv_wait)
    TextView tvWait;
    @BindView(R.id.layout_zc)
    LinearLayout layoutZc;
    @BindView(R.id.tmv_track)
    TextureMapView textureMapView;
    private RecyclerView mRecyclerView;
    @BindView(R.id.btn_xj)
    TextView btnPayType;

    /**
     * DATA
     */
    private BillingTypeAdapter mAdapter;
    private LoadManager mLoadManager;
    private String orderNo;

    /**
     * 1-司机代付 2-现金支付
     */
    //private int payType;
    public static void show(Context context, String orderNo) {
        Intent intent = new Intent(context, OrderGatheringActivity.class);
        intent.putExtra("ORDER_NO", orderNo);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_order_gathering;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            orderNo = bundle.getString("ORDER_NO");
        }
        return !TextUtils.isEmpty(orderNo);
    }


    /**
     * 收到微信付款提醒
     */
    private void getUndoneOrder(final String money) {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("提醒");
                    builder.setCancelable(false);
                    builder.setMessage("您收到" + money + "微信付款。");
                    builder.setNegativeButton("返回首页", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                    builder.create().show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        textureMapView.onCreate(savedInstanceState);
        super.init(savedInstanceState);
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(layoutBase, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webOrderInfo();
            }
        });
    }

    @Override
    protected void initData() {
        webOrderInfo();
        super.initData();
        CancelUtils.setWxPayRefresh(this);
        CancelUtils.setPayRefresh(this);
    }

    /**
     * 轨迹绘制
     */
    private void drawTrackOnMap(List<LatLng> latLngs) {
        if (latLngs != null && !"[]".equals(latLngs.toString())) {
            LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
            PolylineOptions polylineOptions = new PolylineOptions();
            polylineOptions.color(Color.BLUE).width(20);
            if (latLngs.size() > 0) {
                // 起点
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latLngs.get(0))
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                textureMapView.getMap().addMarker(markerOptions);
            }
            if (latLngs.size() > 1) {
                // 终点
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latLngs.get(latLngs.size() - 1))
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                textureMapView.getMap().addMarker(markerOptions);
            }
            for (LatLng latLng : latLngs) {
                polylineOptions.add(latLng);
                boundsBuilder.include(latLng);
            }
            textureMapView.getMap().addPolyline(polylineOptions);
            textureMapView.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 80));
        }
    }

    @OnClick({R.id.tv_extra_charges, R.id.tv_regulation, R.id.btn_wx, R.id.btn_xj})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_extra_charges://额外费用
                webExtraChargesList();
                break;
            case R.id.tv_regulation://计费规则
                ExpenseStandardActivity.show(mContext);
                break;
            case R.id.btn_wx://微信支付
                webGetWxCode();
                break;
            case R.id.btn_xj://收款
                webPay();
                break;
        }
    }

    private void dialogXj() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("确认已收到客户现金付款？");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                webOrderSettleAccounts();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    /**
     * 订单详情
     */
    private void webOrderInfo() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/getOrderDetail", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<OrderInfo>>() {
                }.getType();
                RspModel<OrderInfo> rspModel = getAnalysisBase(mLoadManager, response, type, "订单详情");
                if (rspModel == null) {
                    mLoadManager.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            OrderInfo orderInfo = rspModel.getData();
                            if ("1".equals(orderInfo.getIswaittimeout())) {//1超时等待
                                layoutWait.setVisibility(View.VISIBLE);
                                layoutZc.setVisibility(View.GONE);
                                tvWait.setText(String.format("等待%s分钟\n等待费%s元", orderInfo.getWaittime(), orderInfo.getWaitmoney()));
                            } else {//0未超时等待
                                if (layoutWait != null) {
                                    layoutWait.setVisibility(View.GONE);
                                    layoutZc.setVisibility(View.VISIBLE);
                                    valueShow(orderInfo);
                                    Type typeTrack = new TypeToken<List<LatLng>>() {
                                    }.getType();
                                    List<LatLng> trackList = new Gson().fromJson(orderInfo.getLocusdata(), typeTrack);
                                    if (trackList != null && "[]".equals(trackList.toString())) {
                                        trackList.add(new LatLng(Double.parseDouble(orderInfo.getChufalat()), Double.parseDouble(orderInfo.getChufalong())));
                                        trackList.add(new LatLng(Double.parseDouble(orderInfo.getMudilat()), Double.parseDouble(orderInfo.getMudilong())));
                                    }
                                    drawTrackOnMap(trackList);
                                }
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 微信二维码支付
     */
    private void webGetWxCode() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/payOrderByWeChat", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "微信二维码支付");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null) {
                            onDialogWxQrCode(rspModel.getData());
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 订单现金结算
     */
    private void webOrderSettleAccounts() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/cashOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                onDismiss();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<OrderInfo>>() {
                }.getType();
                RspModel<OrderInfo> rspModel = getAnalysis(response, type, "订单现金结算");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            App.getInstance().showMessage("收款成功！");
                            finish();
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 获取微信支付参数
     */
    private void webPay() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/daifuOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<PayReqEntity>>() {
                }.getType();
                RspModel<PayReqEntity> rspModel = getAnalysis(response, type, "生成支付信息");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            Wechat.pay(rspModel.getData());
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 额外费用对话框
     */
    private void onDialogExtraCharges(final List<BillingType> list) {
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_other_charges, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.BOTTOM);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        final CustomDialog dialog = builder.create();
        mRecyclerView = layout.findViewById(R.id.recycler_view);
        final ClearTextIconEditText editText = layout.findViewById(R.id.ed_price);

        initList(list);
        layout.findViewById(R.id.next_step).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CharSequence price = editText.getText();
                if (TextUtils.isEmpty(price)) {
                    App.getInstance().showMessage("请输入费用!");
                } else {
                    webAddOtherMoney(String.valueOf(price), list.get(selectPosition).getValue());
                    dialog.cancel();
                }
            }
        });

        layout.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        dialog.show();
    }

    /**
     * 添加额外费
     */
    private void webAddOtherMoney(final String otherMoney, String content) {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("othermoneytxt", content);
        asyncHttpPostFormData.addFormData("othermoney", otherMoney);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/othermoneyOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 添加额外费");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getCode() == 200) {
                    if (rspModel.isStatus()) {
                        tvExtraCharges.setText(String.valueOf(otherMoney + "元"));
                        webOrderInfo();
                    } else {
                        App.getInstance().showMessage(rspModel.getMessage());
                    }
                } else {
                    App.getInstance().showMessage(rspModel.getMessage());
                }
            }
        });
    }


    private void onDialogWxQrCode(String url) {
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_wx_qrcode, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.CENTER);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        final CustomDialog dialog = builder.create();
        AppCompatImageView ivQrCodePay = layout.findViewById(R.id.iv_qr_code_pay);
        Bitmap mBitmap = CodeUtils.createImage(url, 180, 180, null);
        ivQrCodePay.setImageBitmap(mBitmap);
        dialog.show();
    }

    private int selectPosition;

    /**
     * 初始化列表
     */
    private void initList(List<BillingType> list) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL, R.drawable.shape_divider_line, 16, false));

        mAdapter = new BillingTypeAdapter(new RecyclerViewAdapter.AdapterListenerImpl<BillingType>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<BillingType> holder, BillingType data, int position) {
                super.onItemClick(holder, data, position);
                for (BillingType type : mAdapter.getDataList()) {
                    type.setSelected(false);
                }
                selectPosition = position;
                mAdapter.getDataList().get(position).setSelected(true);
                mAdapter.notifyDataSetChanged();// 刷新显示
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.replace(list);
    }


    /**
     * 获取额外费用列表
     */
    private void webExtraChargesList() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("chosetype_id", "2");
        okHttpClient.post(Common.Constant.API_IP + "api/Order/ChoseContentList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<List<Reason>>>() {
                }.getType();
                RspModel<List<Reason>> rspModel = getAnalysis(response, type, "获取额外费用列表");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            List<BillingType> typeList = new ArrayList<>();
                            for (Reason reason : rspModel.getData()) {
                                BillingType billingType = new BillingType();
                                billingType.setKey(reason.getId());
                                billingType.setValue(reason.getContent());
                                typeList.add(billingType);
                            }
                            onDialogExtraCharges(typeList);
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @BindView(R.id.tv_start_money)
    TextView tvStartMoney;
    @BindView(R.id.tv_beyond_money)
    TextView tvBeyondMoney;
    @BindView(R.id.tv_await)
    TextView tvAwait;
    @BindView(R.id.tv_discount_coupon)
    TextView tvDiscountCoupon;
    @BindView(R.id.tv_extra_charges_name)
    TextView tvExtraChargesName;
    @BindView(R.id.tv_extra_charges)
    TextView tvExtraCharges;
    @BindView(R.id.tv_all_mileage)
    TextView tvAllMileage;
    @BindView(R.id.tv_all_in_cost)
    TextView tvAllInCost;
    @BindView(R.id.tr_view)
    TableRow tableRow;
    @BindView(R.id.tv_subsidy_name)
    TextView tvSubsidyName;
    @BindView(R.id.tv_subsidy_price)
    TextView tvSubsidyPrice;

    /**
     * 数据显示
     *
     * @param info 订单信息
     */
    private void valueShow(OrderInfo info) {
        tvStartMoney.setText(String.format("%s公里%s元",info.getQibukm(),info.getQibumoney()));
        tvBeyondMoney.setText(String.format("%s公里%s元",info.getChaochukm(),info.getChaochumoney()));
        tvAwait.setText(String.format("%s分钟%s元",info.getWaittime(),info.getWaitmoney()));
        tvDiscountCoupon.setText(String.format("-%s元",info.getDiscountmoney()));
        if (!"0.00".equals(info.getOthermoney())) {
            tvExtraCharges.setText(String.format("%s元",info.getOthermoney()));
        }
        tvAllMileage.setText(String.format("%s公里",info.getDrivetotalmile()));
        tvAllInCost.setText(String.format("%s元",info.getMoney()));
        if (info.getTempname() != null && !"".equals(info.getTempname())) {
            tableRow.setVisibility(View.VISIBLE);
            tvSubsidyName.setText(info.getTempname());
            tvSubsidyPrice.setText(String.format("%s元",info.getTempprice()));
        }
    }

    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 40) {//收到微信付款提醒
            getUndoneOrder(message);
        } else if (type == 1) {//微信代付成功
            finish();
        }
    }
}
